package com.haiertvbic.tvnow.callback;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import com.haiertvbic.tvnow.network.WebData;
import com.haiertvbic.tvnow.util.Constant;
import com.haiertvbic.tvnow.util.SLog;

public class JsonService {
	public static void paserMoreTv(final MoreTv moreTvCallback) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				String spec = "http://openapi.moretv.com.cn/openApi/Service/logon";
				Map<String, String> parmas = new HashMap<String, String>();
				String mac = Constant.MAC;
				parmas.put("mac", mac);
				String content = null;
				try {
					InputStream is = new WebData(spec).PostDataStream(parmas);
					content = convertStreamToString(is);
					JSONObject json = new JSONObject(content);
					String status = json.getString("status");
					String token = json.getString("token");
					String userId = json.getString("userId");
					moreTvCallback.returnData(userId, token);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				SLog.d("", content + "");
			}
		}).start();
	}

	/**
	 * 把流转换为字符串。<br>
	 * 
	 * @param is
	 *            InputStream<br>
	 * @return str String<br>
	 */
	private static String convertStreamToString(InputStream is) {
		// 字节流-->字符流
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			// 一行一行读取数据
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return sb.toString();
	}
}
